package com.jplus.plugin.mybatis;

import java.util.List;

import com.jplus.core.core.ApplicationContext;
import com.jplus.core.core.beans.BeanDefinition;
import com.jplus.core.core.beans.BeanKey;
import com.jplus.core.fault.InitializationError;
import com.jplus.core.plugin.ImportSelector;
import com.jplus.core.utill.JUtil;
import com.jplus.core.utill.clazz.ClassSearchUtil;
import com.jplus.plugin.mybatis.EnableMybatis.MYBATIS;

public class MybatisConfigurationSelector implements ImportSelector {
	private String DEF_MYBATIS = "com.jplus.plugin.mybatis.MybatisConfigurationProxy";

	public static boolean ENABLE = false;
	public static String[] CONFIG = new String[2];

	@Override
	public String[] selectImports(ApplicationContext context) {
		try {
			String daoPkg = getProp(context, MYBATIS.DAO_PACKAGE);
			String xmlPkg = getProp(context, MYBATIS.XML_PATH);
			if (!JUtil.isEmpty(daoPkg) || !JUtil.isEmpty(xmlPkg)) { // 检测是否开启
				// 2.创建代理BeanKey
				BeanKey key = new BeanKey(Class.forName(DEF_MYBATIS));
				// 2扫描所有Dao
				List<Class<?>> listDao = ClassSearchUtil.getListIsInterface(daoPkg);
				for (Class<?> cla : listDao) {
					// 4.创建代理对象
					BeanDefinition bd = context.registerBean(cla);
					bd.addProxyList(key);
				}
			}
			ENABLE = true;
			return new String[] { DEF_MYBATIS };
		} catch (Exception e) {
			throw new InitializationError(e);
		}
	}

	public String getProp(ApplicationContext context, MYBATIS key) {
		return context.getEnvironment().getProp(key.getValue());
	}

}
